/*
 * @Author: Wxx
 * @Date: 2022-02-22 16:37:40
 * @LastEditors: Wxx
 * @LastEditTime: 2022-02-22 16:59:58
 * @Description:
 */
import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
const MyContext = React.createContext();
export default function App() {
  const [list, setList] = useState([]);
  const [info, setInfo] = useState("");
  useEffect(() => {
    axios.get("test.json").then((res) => {
      setList(res.data.data.films);
    });
  }, []);
  return (
    <MyContext.Provider
      value={{
        text: "您好",
        info,
        onClick: (info) => {
          setInfo(info);
        },
      }}
    >
      <div style={{ position: "relative" }}>
        <div style={{ display: "flex", width: "840px", overflow: "auto" }}>
          {list.map((item) => (
            <FileItem key={item.filmId} item={item} />
          ))}
        </div>

        <FilmDetail />
      </div>
    </MyContext.Provider>
  );
}

/**
 * useContext接收一个 context 对象（React.createContext 的返回值）并返回该 context 的当前值。
 * 当前的 context 值由上层组件中距离当前组件最近的 <MyContext.Provider> 的 value prop 决定。
 */
function FileItem(props) {
  const { name, poster, synopsis } = props.item;
  const value = useContext(MyContext);
  return (
    <div onClick={() => value.onClick(synopsis)}>
      <img src={poster} alt={name} />
      <div>
        <h4>{name}</h4>
      </div>
    </div>
  );
}

function FilmDetail(props) {
  const value = useContext(MyContext);
  return (
    <div
      style={{
        width: "300px",
        background: "pink",
      }}
    >
      <h2>当前电影详情：</h2> {value.info}
    </div>
  );
}
